package cn.accjiyun.controller.society;

import cn.accjiyun.common.controller.BaseController;
import cn.accjiyun.common.entity.PageModel;
import cn.accjiyun.common.entity.QueryEntity;
import cn.accjiyun.entity.society.Relative;
import cn.accjiyun.entity.society.SocietyUser;
import cn.accjiyun.service.society.RelativeService;
import cn.accjiyun.service.society.SocietyUserService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/2.
 */
@Controller
@RequestMapping("/admin/society")
public class AdminRelativeController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminRelativeController.class);

    private static String addRelativePage = getViewPath("/admin/society/relative-add");
    private static String relativeListPage = getViewPath("/admin/society/relative-list");

    @Autowired
    private RelativeService relativeService;
    @Autowired
    private SocietyUserService societyUserService;

    @InitBinder({"relative"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("relative.");
    }

    /**
     * 创建家庭成员
     *
     * @param relative 家庭成员实体
     * @return Map<String,Object>
     */
    @RequestMapping("/createRelative")
    @ResponseBody
    public String createRelative(HttpServletRequest request,
                                @ModelAttribute("relative") Relative relative) {
        JsonObject resultJson = new JsonObject();
        try {
            int userId = Integer.valueOf(request.getParameter("userId"));
            relative.setSocietyUserByUserId(societyUserService.querySocietyUserById(userId));
            relativeService.createRelative(relative);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/society/relativeList");
        } catch (Exception e) {
            logger.error("AdminRelativeController.createSysUser()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/deleteRelative")
    @ResponseBody
    public String delete(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] relativeIdsString = request.getParameter("relativeId").split(",");
            int[] relativeIds = new int[relativeIdsString.length];
            for (int i = 0; i < relativeIdsString.length; i++) {
                relativeIds[i] = Integer.valueOf(relativeIdsString[i]);
            }
            if (relativeIdsString != null && relativeIdsString.length > 0) {
                relativeService.deleteRelative(relativeIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminRelativeController.delete()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    /**
     *  分页查询家庭成员信息
     * @param request
     * @return
     */
    @RequestMapping("/getRelativeList")
    @ResponseBody
    public String getRelativeList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map likeStrings = new HashMap();
            likeStrings.put("relativeName", request.getParameter("keyword"));
            queryEntity.setLikeStrings(likeStrings);
            PageModel<Relative> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<Relative> relativeList = relativeService.queryRelativePage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (Relative relative : relativeList) {
                JsonObject list = new JsonObject();
                list.addProperty("relativeId", relative.getRelativeId());
                list.addProperty("relationship", relative.getRelationship());
                list.addProperty("relativeName", relative.getRelativeName());
                list.addProperty("sex", relative.getSex());
                list.addProperty("nation", relative.getNation());
                list.addProperty("mobile", relative.getMobile());
                list.addProperty("email", relative.getEmail());
                list.addProperty("address", relative.getAddress());
                list.addProperty("userId", relative.getSocietyUserByUserId().getUserId());
                list.addProperty("username", relative.getSocietyUserByUserId().getUsername());
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminRelativeController.getRelativeList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/updateRelative")
    @ResponseBody
    public String updateRelative(HttpServletRequest request, @ModelAttribute("relative") Relative relative) {
        JsonObject resultJson = new JsonObject();
        try {
            int userId = Integer.valueOf(request.getParameter("userId"));
            relative.setSocietyUserByUserId(societyUserService.querySocietyUserById(userId));
            relativeService.updateRelative(relative);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminRelativeController.updateRelative()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/relativeAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("societyUserList", getSocietyUserList((byte)2));
        model.setViewName(addRelativePage);
        return model;
    }

    @RequestMapping("/relativeList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("societyUserList", getSocietyUserList((byte)2));
        model.setViewName(relativeListPage);
        return model;
    }

    public List<SocietyUser> getSocietyUserList(byte roleId) {
        QueryEntity queryEntity = new QueryEntity();
        Map eqParams = new HashMap();
        eqParams.put("societyRoleByRoleTypeId.roleTypeId", roleId);
        queryEntity.setEqParams(eqParams);
        PageModel<SocietyUser> pageModel = new PageModel<>();
        pageModel.setPageNo(1);
        pageModel.setPageSize((int)societyUserService.queryAllSocietyUserCount());
        return societyUserService.querySocietyUserPage(queryEntity, pageModel);
    }
}
